import Vue from 'vue'
import Vuex from 'vuex'
import {getRequest} from "@/utils/api";
import SockJS from 'sockjs-client'
import Stomp from 'stompjs'

Vue.use(Vuex)
const now = new Date();
// vuex，页面一刷新数据就还原
const store = new Vuex.Store({
    state: {
        router: [],
        sessions: [],
        admins: [],
        currentAdmin: JSON.parse(window.sessionStorage.getItem("user")),
        // 当前会话信息 （当前聊天的用户）
        currentSession: null,
        filterKey: '',
        stomp: null
    },
    getters: {},

    // 同步更改state中的值
    mutations: {
        initRoutes(state, router) {
            state.router = router;
        },
        changeCurrentSession(state, currentSession) {
            state.currentSession = currentSession;
        },
        addMessage(state, msg) {
            // msg:接收者的信息
            let mss = state.sessions[state.currentAdmin.username + '#' + msg.to];
            if (!mss) {
                Vue.set(state.sessions, state.currentAdmin.username + '#' + msg.to, []);
            }
            state.sessions[state.currentAdmin.username + '#' + msg.to].push({
                content: msg.content,
                date: new Date(),
                self: !msg.noSelf
            })
        },
        INIT_DATA(state) {
            let data = localStorage.getItem('vue-chat-session');
            //console.log(data)
            if (data) {
                state.sessions = JSON.parse(data);
            }
        },
        INIT_ADMIN(state, data) {
            state.admins = data;
        }
    },
    actions: {
        connect(context) {
            context.state.stomp = Stomp.over(new SockJS("/ws/ep"));
            let token = window.sessionStorage.getItem("token");
            context.state.stomp.connect({'Auth-Token': token}, success => {
                context.state.stomp.subscribe("/user/queue/chat", msg => {
                    let receiveMsg = JSON.parse(msg.body);
                    console.log(receiveMsg);
                    receiveMsg.notSelf = true;
                    receiveMsg.to = receiveMsg.from;
                    context.commit('addMessage', receiveMsg)
                })
            }, error => {
            })
        },


        // FriendChat中调用
        initData(context) {
            getRequest("/chat/admin").then(resp => {
                if (resp) {
                    context.commit('INIT_ADMIN', resp)
                }
            })

        }
    },
    modules: {}
})

store.watch(function (state) {
    return state.sessions
}, function (val) {
    console.log('CHANGE: ', val);
    localStorage.setItem('vue-chat-session', JSON.stringify(val));
}, {
    deep: true/*这个貌似是开启watch监测的判断,官方说明也比较模糊*/
})

export default store;
